package com.bwie.controller;

import com.bwie.pojo.TbGoods;
import com.bwie.pojo.User;
import com.bwie.service.TbGoodsService;
import com.bwie.service.UserService;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("tbgoods")
@Api(tags = "tb商品列表")
public class TbGoodsController {


    @Autowired
    TbGoodsService tbGoodsService;

    @Autowired
    UserService userService;


    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     * @description: 商品列表查询
     * @author: xushuaihang
     * @Date: 2024/6/17 12:03
     * @param:
     * @return: com.bwie.utils.R
    **/
    @ApiOperation("tb商品列表")
    @PostMapping("/tbgoodsList")
    public R tbgoodsList(){
        return tbGoodsService.tbgoodsList();
    }



    /**
     * @description: 商品列表查询
     * @author: xushuaihang
     * @Date: 2024/6/17 12:03
     * @param:
     * @return: com.bwie.utils.R
    **/
    @ApiOperation("tb根据id查看详情")
    @PostMapping("/getTbgoodsById/{id}")
    public R getTbgoodsById(@PathVariable(name = "id")Integer id, @RequestHeader(name = "token")String token){

        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("id", Integer.class);

        User byId = userService.getById(userId);

        TbGoods tbGoods = tbGoodsService.getTbgoodsById(id);

        ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();

        zSetOperations.incrementScore("browseNum",id+"",1);

        return R.ok().data("tbGoods",tbGoods).data("userRole",byId.getUserRole());

    }
    
   
    /**
     * @description:同步至数据库以保证数据持久化，保持redis和数据库数据一
     * @author: xushuaihang
     * @Date: 2024/6/17 12:29
     * @param: 
     * @return: void
    **/
    @Scheduled(cron = "0 0/3 * * * ?")
    public void  timingTbGoodsBrowseNum(){

        ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple<String>> browseNum = zSetOperations.rangeWithScores("browseNum", 0, -1);
        for (ZSetOperations.TypedTuple<String> stringTypedTuple : browseNum) {

            TbGoods byId = tbGoodsService.getById(Integer.valueOf(stringTypedTuple.getValue()));
            
            byId.setBrowseNum(stringTypedTuple.getScore().intValue());
            
            tbGoodsService.updateById(byId);

        }

        System.out.println("定时将浏览量同步到mysql中");

    }





}
